package dnl.ui;

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import javax.swing.JLabel;

import dnl.util.ui.Clicker;

/**
 * 
 * @author Daniel Ore
 *
 */
public class LinkLabel extends JLabel {

	private URL url;
	
	public LinkLabel() {
		registerListener();
		this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
	}
	
	public LinkLabel(URL url) {
		this(url.toString(), url);
	}
	
	public LinkLabel(String label, URL url) {
		setLabelAndLink(label, url);
		this.url = url;
		registerListener();
		this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
	}

	public LinkLabel(String label, String urlString) throws MalformedURLException {
		this(label, new URL(urlString));
	}

	public LinkLabel(String urlString) throws MalformedURLException {
		this(urlString, new URL(urlString));
	}

	public void setLink(URL url){
		setLabelAndLink(url.toString(), url);
	}
	
	public void setLabelAndLink(String label, URL url){
		this.url = url;
		setText("<html><A HREF="+url+">"+label+"</A></html>");
	}
	
	private void registerListener(){
		Clicker clicker = new Clicker(this, "");
		clicker.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					Desktop.getDesktop().browse(url.toURI());
				} catch (IOException e1) {
					e1.printStackTrace();
				} catch (URISyntaxException e1) {
					e1.printStackTrace();
				}
			}
		});
	}
	
}
